package com.my.jli.controller;

import com.my.jli.Service.MyFileService;
import com.my.jli.entity.MyFile;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @ClassName MyFileController
 * @Description
 * @Author MaYu
 * @Date 2022/3/28 18:49
 * @Version 1.0
 **/
@Controller
@RequestMapping("/file")
public class MyFileController {

    @Value("${file-save-path}")
    private String fileSavePath;

    private final Logger logger = LoggerFactory.getLogger(MyFileController.class);

    private MyFileService myFileService;
    @Autowired
    public void setMyFileService(MyFileService myFileService) {
        this.myFileService = myFileService;
    }

    @GetMapping("/download")
    public void download(Integer id, HttpServletResponse response){
        MyFile myFile = myFileService.getById(id);
        if (myFile != null){//查询到文件信息后
            String realPath = myFile.getFilepath();
            try {
                //获取文件输入流
                FileInputStream fileInputStream = new FileInputStream(fileSavePath + "/" +realPath);
                //附件下载
                response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(myFile.getFilename(), "UTF-8"));
                //获取响应输出流
                ServletOutputStream outputStream = response.getOutputStream();
                //文件拷贝
                IOUtils.copy(fileInputStream, outputStream);
                //关闭流
                fileInputStream.close();
                outputStream.close();

                logger.info("有人下载了文件：" + myFile.getId() + ":" + myFile.getFilename());
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("文件下载失败：" + myFile.getId() + ":" + myFile.getFilename());
            }
        }
    }
}
